import FilePreviewComp from './FilePreview.vue'
import StreamPreviewComp from './StreamPreview.vue'
import ContentEditorComp from './ContentEditor.vue'
import { createComponent, unmountComponent } from './util'

// 用于管理所有实例
const instances: any[] = []

// 安全卸载组件实例
const safeUnmountComponent = (instance: any) => {
  try {
    if (instance && instance.vnode) {
      unmountComponent(instance)
      const idx = instances.indexOf(instance)
      if (idx > -1) instances.splice(idx, 1)
    }
  } catch (e) {
    const idx = instances.indexOf(instance)
    if (idx > -1) instances.splice(idx, 1)
  }
}

// 通用创建方法
const showComponent = (options: any, Comp: any) => {
  const { onClose, ...rest } = options || {}
  let instance: any = null
  instance = createComponent(
    Comp,
    {
      ...rest,
      onClose: () => {
        onClose && onClose()
        safeUnmountComponent(instance)
      }
    },
    null
  )
  instances.push(instance)
  return instance
}

export const FilePreview = (options: any) => showComponent(options, FilePreviewComp)
export const StreamPreview = (options: any) => showComponent(options, StreamPreviewComp)
export const ContentEditor = (options: any) => showComponent(options, ContentEditorComp)

export default { FilePreview, StreamPreview, ContentEditor }
